# -*- coding: utf-8 -*-
"""
Created on Thu Aug 30 09:52:15 2018

@author: Who

链道财经
http://block.igo321.com/

"""
import requests
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def post_html_text(url, data):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_zx(url, data):
    text = post_html_text(url, data)
    if not text:
        return None
    text = eval(text)

    data = text['data']
    dates = [date['date'][:10] for date in data]
    return dates


def count_process_one():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        data = {
            'page': a,
            'cid': '1'
        }
        url = 'http://block.igo321.com/article/api/list-more'
        dates = get_dates_zx(url, data)
        if not dates:
            break
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        print('----链道财经资讯第{}页获取中----'.format(a))
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '链道财经'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
